<script setup lang="ts">
const props = defineProps<{ id: number }>();
const count = ref(1);
const { data, error } = useFetch(`/products/${props.id}`).json<Product>();
const cart = useCartStore();
const router = useRouter();
const notification = useNotificationStore();
const addCartHandler = (product: Product) => {
  cart.addItem(product, count.value);

  router.push('/cart');

  notification.addNotice({
    id: Date.now(),
    message: '添加成功',
    status: 'success',
    duration: 3000,
  });
};
</script>

<template>
  <BackButton></BackButton>
  <div class="product" v-if="!error && data">
    <div class="img-wrap">
      <img :src="data.image_url" :alt="data.name" />
    </div>
    <div class="info">
      <h2 class="name">{{ data.name }}</h2>
      <p class="desc">{{ data.description }}</p>
      <div class="price-wrap">
        <h3 class="price">{{ data.price.toFixed(2) }}</h3>
        <Counter v-model:count="count"></Counter>
      </div>
    </div>
    <BottomButton @click="addCartHandler(data)">加入购物车</BottomButton>
  </div>
  <p class="msg" v-else-if="error">--- 数据异常 ---</p>
</template>

<style lang="scss" scoped>
.product {
  .img-wrap {
  }

  .info {
    padding: 20rem;
    .name {
      font-size: 20rem;
    }
    .desc {
      font-size: 14rem;
      color: var(--light-color);
    }
    .price-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .price {
        font-size: 16rem;
        &::before {
          content: '￥';
        }
      }
    }
  }
}
.msg {
  text-align: center;
  font-size: 16rem;
}
</style>
